using System.ServiceModel;

namespace Sogeti.Guidelines.WCF.Extensions
{
    public class InstanceItemsExtension : IExtension<InstanceContext>
    {
        public static InstanceItemsExtension Current
        {
            get
            {
                if (OperationContext.Current == null)
                    return null;

                var instanceContext = OperationContext.Current.InstanceContext;
                return GetExtensionFrom(instanceContext);
            }
        }

        public static InstanceItemsExtension GetExtensionFrom(InstanceContext instanceContext)
        {
            lock (instanceContext)
            {
                var extension = instanceContext.Extensions.Find<InstanceItemsExtension>() ??
                                AttachExtension(instanceContext);
                return extension;
            }
        }

        private static InstanceItemsExtension AttachExtension(InstanceContext context)
        {
            var extension = new InstanceItemsExtension(context);
            context.Extensions.Add(extension);

            return extension;
        }


        public InstanceItems Items;

        public InstanceItemsExtension(InstanceContext context)
        {
            Items = new InstanceItems(context);
        }

        public void Attach(InstanceContext owner)
        {
        }

        public void Detach(InstanceContext owner)
        {
        }
    }
}